package com.buihha.audiorecorder;

import java.io.IOException;

import xtom.frame.XtomObject;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;

public class Media extends XtomObject {
	private String path;
	private MediaPlayer mPlayer;
	private int duration;
	private OnCompletionListener listener;
	private OnCompleteListener cListener;
	private OnStopListener stopListener;

	public Media(String path, OnCompleteListener mListener) {
		this.cListener = mListener;
		this.path = path;
		try {
			mPlayer = new MediaPlayer();
			mPlayer.setDataSource(path);
			mPlayer.prepare();
			duration = mPlayer.getDuration();
			listener = new OnCompletionListener() {

				@Override
				public void onCompletion(MediaPlayer mp) {
					mPlayer.release();
					mPlayer = null;
					if (cListener != null)
						cListener.onComplete(mp);
				}
			};
			mPlayer.setOnCompletionListener(listener);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// stop();
	}

	/**
	 * 获取语音时长
	 * 
	 * @return 喵
	 */
	public int getDuration() {
		return duration / 1000;
	}

	public void start() throws IOException {
		if (mPlayer == null) {
			mPlayer = new MediaPlayer();
			mPlayer.setDataSource(path);
			mPlayer.prepare();
			mPlayer.setOnCompletionListener(listener);
		}
		mPlayer.start();
	}

	public void stop() {
		if (mPlayer != null) {
			mPlayer.stop();
			mPlayer.release();
			mPlayer = null;
		}
		if (stopListener != null)
			stopListener.onStop(mPlayer);
	}

	public boolean isPlaying() {
		return mPlayer == null ? false : mPlayer.isPlaying();
	}

	public String getPath() {
		return path;
	}

	public OnStopListener getStopListener() {
		return stopListener;
	}

	public void setStopListener(OnStopListener stopListener) {
		this.stopListener = stopListener;
	}

	public static interface OnCompleteListener {
		public void onComplete(MediaPlayer mp);
	}

	public static interface OnStopListener {
		public void onStop(MediaPlayer mp);
	}
}
